package android.manage;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.main.MemberConst;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.utility.Utility;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.piano_application.R;

/**
 * 회원 목록 페이지
 * */
@SuppressLint("HandlerLeak")
public class Member_list extends Activity implements OnClickListener{
	ProcessGet processGet;
	
	public static ArrayList<MemberDTO> memberlist;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.member_list);
        
        memberList();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	}
	
	public void  memberList(){
        StringBuilder html = new StringBuilder();
        try {
            BufferedReader br = Utility.loadHTML(MemberConst.LIST);
       
       
                while (true) {
                    String line = br.readLine();
                    if (line == null) break;
                    html.append(line + '\n'); 
                }
                
                br.close();

                Member_list.memberlist = new  ArrayList<MemberDTO>(); // 출력 문자열 
              
                JSONObject memberobj = new JSONObject(html.toString());
                JSONArray memberja = memberobj.getJSONArray("data");
                
                
                for (int i = 0; i < memberja.length(); i++) {
                      
                    JSONObject item = memberja.getJSONObject(i);
                    MemberDTO memberdto = new MemberDTO();
                    memberdto.setId(item.getString("id"));
                    memberdto.setNickname(item.getString("nickname"));
                    
                    Member_list.memberlist.add(memberdto);
                }   
                setAdapter(Member_list.memberlist);
                Log.d("D", "Adapter use");
             } catch (Exception e) {
                 Log.d("D", e.toString());
            }
        }
	
	public void setAdapter(ArrayList<MemberDTO> memberlist){
        ListAdapter memberAdapter = new ListAdapter(Member_list.this, R.layout.member_list_row, memberlist);
        ListView member_list = (ListView)findViewById(R.id.lv_member);
        member_list.setAdapter(memberAdapter);
        member_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final long selectId = id;
               Log.d("D", "onItemClick() selectId: " + selectId);

                Toast.makeText(Member_list.this, "항목 클릭" + selectId, Toast.LENGTH_SHORT).show();
            }
        });                 
    }

    //어댑터 클래스
    class ListAdapter extends BaseAdapter {
        Context maincon;
        LayoutInflater Inflater;
        ArrayList<MemberDTO> memberlist;
        int layout;
        
        public ListAdapter(Context context, int layout, ArrayList<MemberDTO> memberlist) {
            maincon = context;
            Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            this.layout = layout;
            this.memberlist = memberlist;

        }

        public int getCount() {
           return memberlist.size();
        }

        public MemberDTO getItem(int position) {
            return (MemberDTO)memberlist.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        // 각 항목의 뷰 생성
        public View getView(int position, View convertView, ViewGroup parent) {
            final int pos = position;
             if (convertView == null) {
                convertView = Inflater.inflate(layout, parent, false);
            }
           
            TextView tv_memberId = (TextView)convertView.findViewById(R.id.tv_memberId);
            tv_memberId.setText(memberlist.get(position).getId());

            TextView tv_memberNickname = (TextView)convertView.findViewById(R.id.tv_memberNickname);
            tv_memberNickname.setText(memberlist.get(position).getNickname());

            Button btnDelete = (Button)convertView.findViewById(R.id.btnDelete);
            // ListView 항목 선택 배경색 활성화 
            btnDelete.setFocusable(false);
            btnDelete.setOnClickListener(new Button.OnClickListener() {
                public void onClick(View v) {
                    String str = memberlist.get(pos).getId() + "님을 탈퇴 시킵니다.";
                    Toast.makeText(maincon, str, Toast.LENGTH_SHORT).show();
                    final LinearLayout linear = (LinearLayout)View.inflate(Member_list.this, R.layout.member_delete, null);
                
                new AlertDialog.Builder(Member_list.this)
                .setTitle("삭제 하시겠습니까? ")
//                .setIcon(R.drawable.icon)
                .setView(linear)
                .setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String id = memberlist.get(pos).getId();
                        //EditText edtPass = (EditText)linear.findViewById(R.id.edtPass);
                        //String pass = edtPass.getText().toString();
                        
                        //Toast.makeText(Notice.this, key +", "+pass, Toast.LENGTH_LONG).show();
                        String addr = MemberConst.DELETE + "?id=" + id;
                        //Toast.makeText(Add.this, addr, Toast.LENGTH_LONG).show();
                        Log.d("D", addr);
                        processGet = new ProcessGet(addr);
                        processGet.start();
                        
                        //Map map = utility.UtilityAndroid.delete(Const.DELETE, id);
//                        String code = (String)map.get("code");
//                        String message = (String)map.get("message");
//                        
//                        Toast.makeText(maincon, message, Toast.LENGTH_LONG).show();
//                        if (code.equals("success") == true){
                        memberList();
//                        }
                        
                    }
                })
                .setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String str = "취소 했습니다.";
                        Toast.makeText(maincon, str, Toast.LENGTH_LONG).show();
                    }
                })
                .show();
                    
                }
            });
            
            
            
            return convertView;
        }
    }
    
    class ProcessGet extends Thread{
        String _addr;

        ProcessGet(String addr) {
            _addr = addr;
        }

        public void run() {

            HttpGet get = new HttpGet(_addr);
            DefaultHttpClient client = new DefaultHttpClient();
            try {
                client.execute(get, responseHandler);
            } 
            catch (Exception e) {;}
        }        
    }
    
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) {
 
            StringBuilder html = new StringBuilder(); 
            String message = "";
            try {                
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while (true) {
                    String line = br.readLine();
                    if (line == null) break;
                    html.append(line + '\n'); 
                }
                br.close();

                JSONObject obj = new JSONObject(html.toString());
                
                String code = obj.getString("code");
                message = obj.getString("message");
                
                if (code.equals("success")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 1;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if (code.equals("fail")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 2;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if ( code.equals("error")){
                	Message msg = msgHandler.obtainMessage();
                    msg.what = 3;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                }
            } catch (Exception e) {
                Message msg = msgHandler.obtainMessage();
                msg.what = 4;
                msg.obj = message;
                msgHandler.sendMessage(msg);
            }
            return html.toString();
        }
    };
	
    Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("D", "handleMessage Call");
            // Log.d("D", "msg.what: " + msg.what);
            
            if (msg.what == 1){
                setResult(RESULT_OK, (new Intent()).setAction("SUCCESS")); // "SUCCESS"를 넘겨준다.
                // 종료 
                memberList();
            }else if (msg.what == 2){
                
            }else if (msg.what == 3){
                
            }else if (msg.what == 4){
            }            
        }
    };
	
			
}
